import { asyncRouterMap, constantRouterMap } from '@/router';
import { generateRoutesByFrontEnd, generateRoutesByServer } from '@/router/routerHelper';
import { defineStore } from 'pinia';
import { store } from '../index';

export interface PermissionState {
  /** 路由表 */
  routers: AppRouteRecordRaw[];
  addRouters: AppRouteRecordRaw[];
  routeInitCompleted: boolean;
  menuTabRouters: AppRouteRecordRaw[];
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    routeInitCompleted: false,
    menuTabRouters: []
  }),
  getters: {},
  actions: {
    generateRoutes(type: 'server' | 'frontEnd' | 'static', routers?: AppCustomRouteRecordRaw[] | string[]): Promise<unknown> {
      return new Promise<void>((resolve) => {
        let routeMap: AppRouteRecordRaw[] = [];
        if (type === 'server') {
          routeMap = generateRoutesByServer(routers as AppCustomRouteRecordRaw[]);
        } else if (type === 'frontEnd') {
          routeMap = generateRoutesByFrontEnd(structuredClone(asyncRouterMap), routers as string[]);
        } else {
          routeMap = structuredClone(asyncRouterMap);
        }
        this.addRouters = routeMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: 'NotFound',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ]);
        this.routers = structuredClone(constantRouterMap).concat(routeMap);
        resolve();
      });
    },
    setRouteInitCompleted(state: boolean) {
      this.routeInitCompleted = state;
    }
  },
  persist: [
    {
      pick: ['routers', 'addRouters', 'menuTabRouters'],
      storage: localStorage
    }
  ]
});

export const usePermissionStoreWithOut = () => usePermissionStore(store);
